//
//  Date+AD.swift
//  ADKit
//
//  Created by Adoma on 2020/10/22.
//

import Foundation

public extension Date {
    
    func string(format: String = "yyyy-MM-dd HH:mm:ss.SSS") -> String {
        let formatter = DateFormatter(format: format)
        return formatter.string(from: self)
    }
    
    func adding(years: Int) -> Date? {
        let calendar = Calendar.current
        let components = DateComponents(year: years)
        return calendar.date(byAdding: components, to: self)
    }
    
    func adding(months: Int) -> Date? {
        let calendar = Calendar.current
        let components = DateComponents(month: months)
        return calendar.date(byAdding: components, to: self)
    }
}

public extension DateFormatter {
    
    convenience init(format: String) {
        self.init()
        self.dateFormat = format
    }
}

public extension Int {
    
    var toDate: Date {
        Date(timeIntervalSince1970: TimeInterval(self))
    }

}

public extension Double {
    
    var toDate: Date {
        Date(timeIntervalSince1970: self)
    }

}


public extension String {
    
    var toDate: Date? {
        guard let interval = TimeInterval(self) else {
            return nil
        }
        return Date(timeIntervalSince1970: interval)
    }

    func date(format: String = "yyyy-MM-dd HH:mm:ss.SSS") -> Date? {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.date(from: self)
    }
}
